<template>
	<view class='popShopTel popShop'>
		<view class="top flex_row_btw_top">
			<view class="left flex_row_start_center">
				<text class="labels">发票信息</text>
			</view>
			<view class="close">
				<up-icon name="close" color="#000" size="16" @tap="closes"></up-icon>
			</view>
		</view>
		<view class="main">
			<view class="settingInvoice">

				<view class="from">
					<view class="col">
						<text class="label">发票抬头：</text>
						<view class="rightLabel">
							<view @click="checkType(1)" class="check1" :class="addressForm.type=='1'?'active':''">个人
							</view>
							<view @click="checkType(2)" class="check2" :class="addressForm.type=='2'?'active':''">单位
							</view>
						</view>
					</view>


					<view class="col" v-if="addressForm.type =='1'">
						<text class="label">个人名称：</text>
						<u--input v-model="addressForm.title1" placeholder="请输入个人名称" clearable maxlength="20"
							 @blur="validateConsignee1"></u--input>
					</view>

					<view class="col" v-if="addressForm.type =='2'">
						<text class="label">单位名称：</text>
						<u--input v-model="addressForm.title2" placeholder="请输入单位名称" clearable maxlength="50"
							 @blur="validateConsignee2"></u--input>
					</view>

					<view class="col" v-if="addressForm.type =='2'">
						<text class="label">纳税人识别号：</text>
						<u--input v-model="addressForm.credit" placeholder="请输入纳税人识别号" clearable maxlength="18"
							 @blur="validateConsignee3"></u--input>
					</view>



					<view class="col">
						<text class="label">发票内容</text>
						<view class="rightLabel">
							<text class="val1">
								商品明细
							</text>
							<text class="val2">
								提示：发票内容将显示详细商品名称与价格信息
							</text>
						</view>
					</view>

					<view class="col">
						<text class="label">手机号码：</text>
						<view class="right">
							<u--input v-model="addressForm.mobile" placeholder="请输入手机号码" clearable maxlength="11"
								type="number" @blur="validateConsignee4"></u--input>
						</view>
					</view>
				</view>


				<view class="btn">
					<button @click="save_address">确定</button>
				</view>

			</view>


		</view>
	</view>

</template>

<script setup>
	import {
		getInvoiceSave,
		invoiceSave
	} from '@/api/order.js'
	import {
		orderInvoice
	} from '@/api/mineOrder.js'
	import {
		ref,
		onMounted,
		defineExpose,
		watch,
		reactive,
		defineEmits
	} from 'vue';
	import {
		onLoad,
		onReady,
		onShow,
		onHide,
		
	} from '@dcloudio/uni-app'
	const orderId = ref('')
	const emit = defineEmits(['closeModel', 'saveModel'])
	// 发票表单数据
	const addressForm = reactive({
		type: '1', // 默认选个人
		title1: '', // 个人名称
		title2: '', // 单位名称
		credit: '', // 纳税人识别号
		mobile: '',
	})

	const invoiceList = ref([]) //发票信息

	// 切换发票类型
	const checkType = (type) => {
		addressForm.type = type; // 更新发票类型
	};

	// 校验收货人姓名（根据你的需求，调整此函数）
	const validateConsignee1 = () => {
		// 去除空格
		addressForm.title1 = addressForm.title1.replace(/\s+/g, '');
		const regex = /^[A-Za-z\u4e00-\u9fa5]{1,20}$/; // 允许字母和汉字
		if (!regex.test(addressForm.title1)) {
			uni.showToast({
				icon: 'none',
				title: '个人名称只能输入1到20个汉字或字母',
			});
		}
	};

	const validateConsignee2 = () => {
		addressForm.title2 = addressForm.title2.replace(/\s+/g, '');
		// 正则表达式允许输入1到50个汉字或字母（大小写）
		const regex = /^[\u4e00-\u9fa5A-Za-z]{1,50}$/;
		if (!regex.test(addressForm.title2)) {
			uni.showToast({
				icon: 'none',
				title: '单位名称只能输入1至50个汉字或字母',
			});
			// addressForm.title2 = ''; // 可以根据需要重置输入框
		}
	};


	const validateConsignee3 = () => {
		addressForm.credit = addressForm.credit.replace(/\s+/g, '');
		// 允许15到18位字母或数字的组合
		const regex = /^[A-Za-z0-9]{15,18}$/;
		if (!regex.test(addressForm.credit)) {
			uni.showToast({
				icon: 'none',
				title: '纳税人识别号格式不正确',
			});
			// addressForm.credit = ''; // 重置输入框
		}
	};

	const validateConsignee4 = () => {
		addressForm.mobile = addressForm.mobile.replace(/\s+/g, '');
		// 正则表达式：校验11位数字（符合手机号格式）
		const regex = /^[0-9]{11}$/;
		if (!regex.test(addressForm.mobile)) { // 使用 addressForm.mobile 来校验手机号
			uni.showToast({
				icon: 'none',
				title: '手机号格式不正确',
			});
			// addressForm.mobile = ''; // 如果需要，清空手机号输入框
		}
	};
	// 保存发票信息
	const save_address = async () => {
		if (addressForm.type == '1' || addressForm.type == 1) {
			// 校验个人名称
			if (!addressForm.title1) {
				uni.showToast({
					icon: 'none',
					title: '请输入个人名称',
				});
				return; // 如果个人名称为空，立即退出，不校验手机号
			} else {
				validateConsignee1(); // 个人名称校验
				if (addressForm.title1 === '') return; // 如果个人名称校验失败，退出
			}

			// 校验手机号
			if (!addressForm.mobile) {
				uni.showToast({
					icon: 'none',
					title: '请输入手机号',
				});
				return; // 如果手机号为空，立即退出
			} else {
				validateConsignee4(); // 手机号校验
				if (addressForm.mobile === '') return; // 如果手机号校验失败，退出
			}
			// 校验手机号
			if (!addressForm.mobile) {
				uni.showToast({
					icon: 'none',
					title: '请输入手机号',
				});
				return; // 如果手机号为空，立即退出
			} else {
				validateConsignee4(); // 手机号校验
				if (addressForm.mobile === '') return; // 如果手机号校验失败，退出
			}
			// return
		}
		// 单位类型发票校验（type === '2'）
		if (addressForm.type == '2' || addressForm.type == 2) {
			// 校验单位名称
			if (!addressForm.title2) {
				uni.showToast({
					icon: 'none',
					title: '请输入单位名称',
				});
				return; // 如果单位名称为空，立即退出
			} else {
				validateConsignee2(); // 单位名称校验
				if (addressForm.title2 === '') return; // 如果单位名称校验失败，退出
			}

			// 校验纳税人识别号
			if (!addressForm.credit) {
				uni.showToast({
					icon: 'none',
					title: '请输入纳税人识别号',
				});
				return; // 如果纳税人识别号为空，立即退出
			} else {
				validateConsignee3(); // 纳税人识别号校验
				if (addressForm.credit === '') return; // 如果纳税人识别号校验失败，退出
			}

			console.log('addressForm.credit', addressForm.credit)
			// 校验手机号
			if (!addressForm.mobile) {
				uni.showToast({
					icon: 'none',
					title: '请输入手机号',
				});
				return; // 如果手机号为空，立即退出
			} else {
				validateConsignee4(); // 手机号校验
				if (addressForm.mobile === '') return; // 如果手机号校验失败，退出
			}
			// return
		}
		let county_name = {
			type: addressForm.type,
			title: addressForm.type == '1' ? addressForm.title1 : addressForm.title2,
			mobile: addressForm.mobile,
			credit: addressForm.type == '2' ? addressForm.credit : '',
		};

		const resp = await invoiceSave(county_name);
		if (resp.code === 1) {
			console.log('invoiceList.value.length', invoiceList.value.length);
			uni.showToast({
				icon: 'none',
				title: resp.msg,
			});
			if (orderId.value != '') {
				setUpdate()
			} else {
				emit('saveModel')
			}

		} else {
			uni.showToast({
				icon: 'none',
				title: resp.msg,
			});
		}
	};

	// 获取发票详情
	const addressDetails = async () => {
		const res = await getInvoiceSave();
		if (res.code === 1) {
			const _data = res.data.list;
			if (_data && _data.length > 0) {
				invoiceList.value = _data; // 修改为响应式更新
				const [firstInvoice, secondInvoice] = _data;
				addressForm.mobile = firstInvoice.mobile; // 更新 mobile
				const setAddressForm = (item) => {
					if (item.type === 1) {
						addressForm.type = '1'; // 更新类型
						addressForm.title1 = item.title; // 更新个人名称
						// console.log('addressForm', addressForm);
					} else if (item.type === 2) {
						addressForm.type = '2'; // 更新类型
						// console.log('addressForm222', addressForm);
						addressForm.title2 = item.title; // 更新单位名称
						addressForm.credit = item.credit; // 更新纳税人识别号
					}
				};
				if (addressForm.type == 2) {
					setAddressForm(firstInvoice);
					setAddressForm(secondInvoice); // 如果有第二个数据则回显
				} else {
					setAddressForm(secondInvoice); // 如果有第二个数据则回显
					setAddressForm(firstInvoice);
				}
				// // 回显第一个和第二个数据
			}else{
				addressForm.type = '1'; // 更新类型
			}
		} else {
			uni.showToast({
				icon: 'none',
				title: res.msg
			});
		}
	};
	//取消
	const closes = () => {
		emit('closeModel')
	}


	const setUpdate = async () => {
		const resp = await orderInvoice({
			id: orderId.value,
			invoice_type: addressForm.type
		});
		if (resp.code === 1) {
			uni.showToast({
				icon: 'none',
				title: resp.msg,
			});
			emit('saveModel')

		} else {
			uni.showToast({
				icon: 'none',
				title: resp.msg,
			});
		}
	}
	defineExpose({
		addressDetails,
		orderId,
		addressForm
	})
</script>

<style scoped lang="less">
	.popShopTel {
		// width: 588rpx;
		// background-image: url(https://zzt-pub.oss-cn-wuhan-lr.aliyuncs.com/clientImg/telBj%402x.png);
		// background-repeat: no-repeat;
		// background-size: 100%;

		.top {
			padding-top: 30rpx;
			padding-right: 30rpx;
		}

		.main {
			margin-top: 20rpx;

			.tip {
				font-weight: 500;
				font-size: 32rpx;
				color: #333333;
				text-align: center;
				margin-bottom: 76rpx;
			}
		}

		.bottom {
			width: calc(100% - 53px);
			margin: 0 auto;

			.btn1 {
				display: inline-block;
				width: 230rpx;
				height: 80rpx;
				background: linear-gradient(113deg, #F2BD6F 0%, #CCA05F 100%);
				border-radius: 20rpx;
				font-family: Source Han Sans CN, Source Han Sans CN;
				font-weight: 500;
				font-size: 32rpx;
				color: #FFFFFF;
				line-height: 80rpx;
				text-align: center;
				font-style: normal;
				text-transform: none;
			}

			.btn {
				display: inline-block;
				width: 230rpx;
				height: 80rpx;
				background: #f0f0f0;
				border-radius: 20rpx;
				font-family: Source Han Sans CN, Source Han Sans CN;
				font-weight: 500;
				font-size: 30rpx;
				color: #333;
				line-height: 80rpx;
				text-align: center;
				font-style: normal;
				text-transform: none;
			}
		}

	}

	.labels {

		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 34rpx;
		color: #2F2F2F;
		box-sizing: border-box;
		padding-left: 30rpx;
	}

	// 设置发票
	.settingInvoice {
		padding: 10rpx 30rpx;
		box-sizing: border-box;

		.from {
			width: 100%;
			display: flex;
			flex-wrap: wrap;
			padding: 30rpx 0;
			box-sizing: border-box;

			.col {
				width: 100%;
				// height: 70rpx;
				display: flex;
				align-items: flex-start;
				margin-bottom: 30rpx;

				.label {
					width: 160rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					height: 100%;
					font-size: 28rpx;
					color: #333333;
					display: flex;
					align-items: flex-start;
					text-align: left;
					font-style: normal;
					padding-top: 7rpx;
					box-sizing: border-box;
				}

				.rightLabel {
					flex: 1;
					height: 100%;
					display: flex;
					flex-wrap: wrap;
					justify-content: space-between;

					.check1 {
						color: #666666;
						height: 66rpx;
						line-height: 66rpx;
						background: #F0F0F0 !important;
						border-radius: 8rpx 8rpx 8rpx 8rpx;
						width: 45%;
						font-family: Source Han Sans CN, Source Han Sans CN;
						font-weight: 400;
						font-size: 26rpx;
						text-align: center;
					}

					.check2 {
						height: 66rpx;
						line-height: 66rpx;
						background: #F0F0F0 !important;
						border-radius: 8rpx 8rpx 8rpx 8rpx;
						width: 45%;
						font-family: Source Han Sans CN, Source Han Sans CN;
						font-weight: 400;
						font-size: 26rpx;
						// background: linear-gradient( 115deg, #F2BD6F 0%, #CCA05F 100%);
						color: #666666;
						text-align: center;
					}

					.active {
						background: linear-gradient(115deg, #F2BD6F 0%, #CCA05F 100%) !important;
						color: #FFF !important;
					}

					.val1 {
						width: 100%;
						display: block;
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 30rpx;
						color: #2F2F2F;
						line-height: 45rpx;
						text-align: left;
						font-style: normal;
						text-transform: none;
						margin-bottom: 10rpx;
					}

					.val2 {
						width: 100%;
						display: block;

						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 26rpx;
						color: #A1A1A1;
						line-height: 40rpx;
						text-align: left;
						font-style: normal;
						text-transform: none;
					}
				}

				.right {
					flex: 1;
					height: 100%;
					display: flex;

					.getPhoneCode {
						padding-left: 20rpx;
						display: flex;
						align-items: center;
						width: 150rpx;
						height: 100%;
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #333;
						font-style: normal;
					}

					.time {
						padding-left: 20rpx;
						display: flex;
						align-items: center;
						width: 150rpx;
						height: 100%;
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #CCA05F;
						font-style: normal;
					}
				}

				.val {
					flex: 1;
				}
			}
		}

		.btn {
			width: 100%;
			padding: 0 30rpx;
			display: flex;
			justify-content: center;
			box-sizing: border-box;
			margin-top: 40rpx;

			button {
				width: 100%;
				height: 88rpx;
				background: linear-gradient(138deg, #EDA55B 0%, #D09A47 100%);
				border-radius: 14rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #FFFFFF;
				line-height: 88rpx;
				font-style: normal;
			}

		}

	}
</style>